<template>
  <div style="overflow-y: hidden">
    <div class="op-btns">
      <div class="left">
        <!-- <px-button type="primary" plain @click="importAction">导入</px-button> -->
        <px-button v-has="'REPORT_DETAIL_EXPORT'" type="primary" plain @click="exportAction">{{
          route.query.id ? "导出数据" : "导出模版"
        }}</px-button>
        <px-button v-has="'REPORT_DETAIL_PRINT'" type="primary" plain @click="printAction">打印</px-button>
        <!-- <px-button v-if="route.query.id" type="danger" @click="deleteAction">删除</px-button> -->
      </div>
      <div class="center">
        <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" inline label-width="90px">
          <px-form-item label="时间" prop="timeRange" style="width: 420px">
            <px-date-picker
              v-model="queryParams.timeRange"
              clearable
              type="daterange"
              range-separator="至"
              start-placeholder="请选择开始时间"
              end-placeholder="请选择结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </px-form-item>

          <px-form-item class="option-item">
            <px-button type="primary" @click="searchAction">查询</px-button>
            <!-- <px-button @click="resetQuery">重置</px-button> -->
          </px-form-item>
        </px-form>
      </div>
      <div class="right" />
    </div>
    <div style="position: relative; box-sizing: border-box; height: calc(100vh - 158px); padding: 16px; overflow-y: hidden">
      <iframe id="reportFrame" :src="templateUrl" width="100%" height="100%" frameborder="0" />
    </div>
    <div class="op-btns footer-btns">
      <div class="right"><px-button v-has="'REPORT_DETAIL_SUBMIT'" type="primary" @click="submitAction">提交</px-button></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { deleteReportRecord } from "@/api/report";
import { onMounted, reactive, toRefs, ref, computed, nextTick } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { useRouter, useRoute } from "vue-router";
import { useNav } from "@/layout/hooks/useNav";
import dayjs from "dayjs";

defineOptions({
  name: "FULLSCREEN_TEMPLATE_DETAIL"
});

const { username } = useNav();
const router = useRouter();
const route = useRoute();

const templateUrl = ref();

const queryParams = reactive({
  timeRange: ""
});
const writeSingleCode = ref();

const submitAction = () => {
  document.getElementById("reportFrame").contentWindow.postMessage("_g().verifyAndWriteReport()", "*");
};
// importExcel_Clean清空导入
// importExcel_Append 增量导入
// importExcel_Cover 覆盖导入
const importAction = () => {
  document.getElementById("reportFrame").contentWindow.postMessage("_g().importExcel_Cover()", "*");
};
const exportAction = () => {
  document.getElementById("reportFrame").contentWindow.postMessage("_g().exportReportToExcel('simple')", "*");
};
const deleteAction = () => {
  PxMessageBox.confirm(`是否该条记录数据？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteReportRecord({ ids: [route.query.id] });
      PxMessage.success("删除成功");
      templateUrl.value = `${window.location.protocol}//${window.location.hostname}:8443/webroot/decision/view/report?viewlet=${route.query.template}&user=${username.value}&__pi__=false&facCode=${localStorage.getItem("facCode") || ""}`;
      localStorage.setItem("listen_report_record_delete", "true");
      setTimeout(() => {
        window.close();
      }, 1500);
    })
    .catch(() => {});
  //window.close()
};
const printAction = () => {
  // document.getElementById('reportFrame').contentWindow.contentPane.noClientPrint(true, true)();
  // let config = JSON.stringify({
  //   printUrl: `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report`,
  //   printType: 0, // 1
  //   isPopUp: true,
  //   pageType: 0,
  //   data: {
  //     reportlets:[{reportlet: `${decodeURIComponent(decodeURIComponent(route.query.template))}`, cmd: 'save_w_content', op: 'write', singleCode: route.query.singleCode}]
  //   }
  // })
  // // console.log('config:' + JSON.stringify(config));
  // // let config = JSON.stringify({ url: templateUrl.value, isPopUp: true });
  // //doURLPrint doURLPDFPrint
  // document.getElementById("reportFrame").contentWindow.postMessage(`FR.doURLPrint(${config})`, "*");
  document.getElementById("reportFrame").contentWindow.postMessage(`_g().noClientPrint(true,true)`, "*");
};
const { VITE_FANRUAN_BASE_URL } = import.meta.env;
function getFileNameWithoutExtension(path) {
  var fileNameWithExtension = path.replace(/^.*[\\\/]/, "");
  return fileNameWithExtension.replace(/\.[^/.]+$/, "");
}

const getUrl = isAction => {
  let baseUrl = `${window.location.protocol}//${window.location.hostname}:8443/webroot/decision/view/report?viewlet=${route.query.template}&user=${username.value}&__pi__=false&facCode=${localStorage.getItem("facCode") || ""}`;
  if (route.query.op && route.query.op == "write") {
    baseUrl = `${baseUrl}&op=write`;
  }
  if (route.query.singleCode || writeSingleCode.value) {
    baseUrl = `${baseUrl}&singleCode=${route.query.singleCode || writeSingleCode.value}`;
  }
  if (!route.query.singleCode || isAction) {
    let startDate = queryParams?.timeRange?.[0] || "";
    let endDate = queryParams?.timeRange?.[1] || "";
    if (startDate && endDate) {
      baseUrl = `${baseUrl}&startDate=${startDate}&endDate=${endDate}`;
    }
    // baseUrl = `${baseUrl}&startDate=${startDate}&endDate=${endDate}`;
  }
  templateUrl.value = baseUrl;
  if (route.query.template) {
    // 使用例子
    let name = getFileNameWithoutExtension(decodeURIComponent(decodeURIComponent(route.query.template)));
    const { VITE_ENV_NAME } = import.meta.env;
    // fac_test 和 uat显示stic图标
    if (VITE_ENV_NAME === "fac_test" || VITE_ENV_NAME === "uat" || VITE_ENV_NAME === "prod") {
      document.title = name || "创新智慧厂务管理平台";
    } else {
      document.title = name || "IFP智慧厂务系统";
    }
  }
};
onMounted(() => {
  let ym = new Date();
  if (route.query.date) {
    ym = new Date(route.query.date);
  }
  // 获取当前月份第一天
  const firstDayOfMonth = dayjs(new Date(ym.getFullYear(), ym.getMonth(), 1)).format("YYYY-MM-DD");
  // 获取当前月份最后一天
  const lastDayOfMonth = dayjs(new Date(ym.getFullYear(), ym.getMonth() + 1, 0)).format("YYYY-MM-DD");
  queryParams.timeRange = [firstDayOfMonth, lastDayOfMonth];
  getUrl(true);
  window.addEventListener("message", function (event) {
    console.log(event);
    let o = `${window.location.protocol}//${window.location.hostname}:8443`;
    if (event.origin !== o) return;
    let code = JSON.parse(event.data)?.reportSingleCode;
    if (code) {
      writeSingleCode.value = code;
      getUrl(true);
    }
  });
});

const searchAction = () => {
  getUrl(true);
};
</script>
<style scoped lang="scss">
.template-content {
  width: 100%;
}

.custom-form-ui {
  height: 38px;

  .px-form-item {
    margin-bottom: 0;
  }
}

.op-btns {
  display: flex;
  padding: 16px;
  margin: 5px 0;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 10%);

  .left {
    flex: 1;
    text-align: left;
  }

  .center {
    flex: 1;
    text-align: center;
  }

  .right {
    flex: 1;
    text-align: right;
  }
}

.footer-btns {
  text-align: right;
}
</style>
